#coding:utf-8
#code by foRK
#QQ:261496481
#扫描单个IP的单个/多个/连续端口

import sys
import socket
import thread
import time

socket.setdefaulttimeout(10)

if len(sys.argv) < 2:
	print 'version 1.0'
	print '%s [scanIP] [PORT]' % sys.argv[0]
	print '%s 192.168.1.1 80' % sys.argv[0]
	print '%s 192.168.1.1 1-1024' % sys.argv[0]
	print '%s 192.168.1.1 80,3389,1314' % sys.argv[0]
	print '%s 192.168.1.1 default' % sys.argv[0]
	sys.exit(1)
	
scanIP = sys.argv[1]
PORT = sys.argv[2]

def ip2num(ip):  #ip 转 num
	ip1 = [int(x) for x in ip.split('.')]
	return ip1[0]<<24 | ip1[1]<<16 | ip1[2]<<8 | ip1[3]

	
def num2ip(num): #num 转 ip
	return '%s.%s.%s.%s' % (  (num & 0xff000000) >> 24,
                              (num & 0x00ff0000) >> 16,
                              (num & 0x0000ff00) >> 8,
                              num & 0x000000ff  )

def scan_port(ip, port):  #核心代码
	try:
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		res = s.connect_ex((ip,port))
		if (res == 0):
			print ip,u":",port,u"port open"
		s.close()
	except:
		print u"port scan error"
		
if __name__=='__main__':  #判断模块
	if '-' in PORT:  #判断输入是否为"1-80"的形式
		port = PORT.split('-') #if PORT=1-80,port = ['1','80']
		port1 = range(int(port[0]), int(port[1]) + 1) #port1=[1, 2, ...., 80]
		ip = num2ip(ip2num(scanIP))
		I1 = 0  #端口列表的第一个
		print u"need scan"+" "+str(len(port1))+" "+u"port"
		t = time.time()
		while I1 < len(port1): 
			thread.start_new_thread(scan_port,(ip,port1[I1]))
			I1 = I1 + 1
			time.sleep(0.03) #休眠时间socket
		print 'used time:%f' % (time.time()-t)
	
	elif ',' in PORT:  #判断输入是否为"1,2,3,4,5,6"的形式
		port = PORT.split(',')  #['1', '2', '3', '4', '5', '6', '7', '8', '9']
		ip = num2ip(ip2num(scanIP))
		I1 = 0  #列表的第一个
		print u"need scan"+" "+str(len(port))+" "+u"port"
		t = time.time()
		while I1 < len(port):
			thread.start_new_thread(scan_port,(ip,int(port[I1])))
			I1 = I1 + 1
			time.sleep(0.003) #休眠时间socket
		print 'used time:%f' % (time.time()-t)
		
	elif PORT == 'd':  #默认扫描模式，扫描常用端口
		port = [21, 22, 23, 25, 80, 135, 139, 445, 1433, 389, 8080]
		ip = num2ip(ip2num(scanIP))
		I1 = 0
		print u"need scan"+" "+str(len(port))+" "+u"port"
		t = time.time()
		while I1 < len(port):
			thread.start_new_thread(scan_port,(ip,int(port[I1])))
			I1 = I1 + 1
			time.sleep(0.03) #休眠时间socket
		print 'used time:%f' % (time.time()-t)
		
	else: #扫描单个端口模式
		port = int(PORT)
		ip = num2ip(ip2num(scanIP))
		t = time.time()
		scan_port(ip, port)
		print 'used time:%f' % (time.time()-t)